package cn.zust.edu.cn;

class Triangle implements IShape {
    Point ptA;
    Point ptB;
    Point ptC;
    private final double edgeA;
    private final double edgeB;
    private final double edgeC;

    public Triangle(Point ptA, Point ptB, Point ptC) {
        this.ptA = ptA;
        this.ptB = ptB;
        this.ptC = ptC;
        this.edgeA = Math.sqrt(Math.pow(ptB.x - ptC.x, 2) + Math.pow(ptB.y - ptC.y, 2));
        this.edgeB = Math.sqrt(Math.pow(ptA.x - ptC.x, 2) + Math.pow(ptA.y - ptC.y, 2));
        this.edgeC = Math.sqrt(Math.pow(ptA.x - ptB.x, 2) + Math.pow(ptA.y - ptB.y, 2));
    }

    @Override
    public double perimeter() {
        return edgeA + edgeB + edgeC;
    }

    @Override
    public double area() {
        double s = (edgeA + edgeB + edgeC) / 2;
        return Math.sqrt(s * (s - edgeA) * (s - edgeB) * (s - edgeC));
    }

    @Override
    public void draw() {
        int maxX = Math.max(Math.max(ptA.x, ptB.x), ptC.x);
        int maxY = Math.max(Math.max(ptA.y, ptB.y), ptC.y);
        for (int y = 0; y <= maxY; y++) {
            for (int x = 0; x <= maxX; x++) {
                if (isOnEdge(new Point(x, y), ptA, ptB, ptC)) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

    private boolean isOnEdge(Point p, Point a, Point b, Point c) {
        return isOnLine(p, a, b) || isOnLine(p, b, c) || isOnLine(p, c, a);
    }

    private boolean isOnLine(Point p, Point a, Point b) {
        int dx = b.x - a.x;
        int dy = b.y - a.y;
        int px = p.x - a.x;
        int py = p.y - a.y;
        return (px * dy == py * dx) && (px >= 0) == (dx >= 0) && (py >= 0) == (dy >= 0)
                && Math.sqrt(px * px + py * py) <= Math.sqrt(dx * dx + dy * dy);
    }

    }
